import { memo } from 'react';
import { InbizIcon, isEditorENV } from '@inbiz/utils';
import { getMessage } from '@inbiz/react';
import { observer } from '@formily/react';
import { useNavigate } from 'react-router-dom';
import { routerPrefix } from 'InbizConfig';

interface IconType {
  className?: string;
  titleOption: {
    value?: string;
    status?: boolean;
  };
  fontSize?: number;
  fontColor?: string;
  iconOption?: any;
  externalAddress: boolean;
  link?: string;
  page?: string;
  jumpType?: boolean;
}
const Iconfont = memo(
  observer((props: IconType) => {
    const {
      className,
      titleOption = {},
      fontSize,
      fontColor,
      iconOption = {},
      externalAddress,
      link,
      page,
      jumpType,
    } = props;
    const { value, status } = titleOption;
    const { type, size, color } = iconOption;
    const history = useNavigate()

    const handleClick = () => {
      if (externalAddress) {
        // 外部地址
        if (!link) return;
        if (!isEditorENV()) {
          let url = '';
          let protocol = window.location.protocol + '//'; // 兼容http和https
          if (link.indexOf('http://') == -1 && link.indexOf('https://') == -1) {
            url = protocol + link;
          } else {
            url = link;
          }
          if (jumpType) {
            window.open(url);
            return;
          }
          window.location.href = url;
        }
      } else {
        // 内部页面
        if (!page || typeof page !== 'string' || page === '') return;
        if (!isEditorENV()) {
          let route = String(page).slice(0, String(page).indexOf(','));
          if (route !== '') {
            if (jumpType) {
              const _ = window.location;
              let url = `${_.origin}${_.pathname}${_.search}#${routerPrefix}${route}`;
              window.open(url);
              return;
            }
            history({
              pathname: `${routerPrefix}${route}`,
            });
          }
        }
      }
    };
    return (
      <div
        className={className}
        style={{
          display: 'flex',
          width: '100%',
          height: '100%',
          alignItems: 'center',
          justifyContent: 'center',
          flexDirection: 'column',
        }}
        onClick={handleClick}
      >
        <InbizIcon
          type={type}
          style={{
            color: color || '',
            fontSize: size || 24,
          }}
        />
        {status && (
          <div style={{ fontSize, color: fontColor, paddingTop: '6px', wordBreak: 'break-word' }}>
            &nbsp;{getMessage(value || '')}&nbsp;
          </div>
        )}
      </div>
    );
  }),
);

export default Iconfont;
